<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 2017/3/30
 * Time: 12:14
 */

namespace app\common\util;


class MenuManager
{
    private static $path = APP_PATH . 'common/data/menus.php';

    public static function getAllMenus()
    {
        return include(self::$path);
    }

    public static function getMenus($tokens = false)
    {
        $menus = self::getAllMenus();
        if (!is_array($tokens)) {
            return $menus;
        }
        foreach ($menus as $k1 => &$m1) {
            if (!in_array($k1, $tokens)) {
                unset($menus[$k1]);
            }
            if (!empty($m1['subs'])) {
                $m1['subs'] = self::filterMenu($m1['subs'], $tokens);
            }
            if (!empty($m1['#subs'])) {
                $m1['#subs'] = self::filterMenu($m1['#subs'], $tokens);
            }
        }
        return $menus;
    }

    public static function getActions($tokens)
    {
        $menus = self::getAllMenus();
        $results = [];

        $func = function($menus) use(&$func,&$results,$tokens){
            foreach ($menus as $k1 => &$m1) {
                if (!in_array($k1, $tokens)) {
                    continue;
                }
                if (!empty($m1['#subs'])) {
                    $k1 = U($k1);
                    $m1['#subs'] = self::filterMenu($m1['#subs'], $tokens);
                    foreach ($m1['#subs'] as $key => $title) {
                        list($url,$act) = explode('#',$key);
                        $results[$k1][] = $act ;
                    }
                }else if(!empty($m1['subs'])){
                    $func($m1['subs']);
                }
            }
        };
        $func($menus);
        return $results;
    }

    private static function filterMenu($menus, $tokens)
    {
        foreach ($menus as $key => &$item) {
            if (!in_array($key, $tokens)) {
                unset($menus[$key]);
            }
            if (!empty($item['subs'])) {
                $item['subs'] = self::filterMenu($item['subs'], $tokens);
            }
            if (!empty($item['#subs'])) {
                $item['#subs'] = self::filterMenu($item['#subs'], $tokens);
            }
        }
        return $menus;
    }
}